package com.example.dotavideo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dotavideo.adapter.VideoAdapter;
import com.example.dotavideo.adapter.YouLikeAdapter;
import com.example.dotavideo.bean.VideoBean;
import com.example.dotavideo.util.CommonLog;
import com.example.dotavideo.util.LogFactory;
import com.nostra13.universalimageloader.core.ImageLoader;

public class VideoActivity extends Activity {

 private VideoBean bean;
 private Context context;
private ArrayList<VideoBean> likeList = new ArrayList<VideoBean>();
@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    context = this;
    setContentView(R.layout.video_detail);
    
    Bundle data = getIntent().getBundleExtra("list");
    bean = (VideoBean) data.getSerializable("video");
    VideoBean bean1 = (VideoBean) data.getSerializable("video1");
    VideoBean bean2 = (VideoBean) data.getSerializable("video2");
    VideoBean bean3 = (VideoBean) data.getSerializable("video3");

    likeList.add(bean1);
    likeList.add(bean2);
    likeList.add(bean3);
    
    
    
    initPlayer();
    
    findViews();
    initInfo();
    
    
  }

private void initInfo() {
	LayoutInflater inflater = LayoutInflater.from(this);
	View header = inflater.inflate(R.layout.detail_listview_header, null);
	
	TextView tvTitle = (TextView) header.findViewById(R.id.tv_title);
	TextView tvDate = (TextView) header.findViewById(R.id.tv_date);
	TextView tvContent = (TextView) header.findViewById(R.id.tv_content);
	tvTitle.setText(bean.getTitle());
	tvDate.setText(bean.getDate());
	
	String detail = bean.getDetail().trim();
	if(null == detail || "null".equals(detail) || "".equals(detail)){
		detail = bean.getTitle();
		tvContent.setText(detail + ",欢迎观看！");
	} else {
		tvContent.setText(detail);
	}
	
	
	ListView listView  = (ListView) findViewById(R.id.lv_vedio);
	YouLikeAdapter adapter = new YouLikeAdapter(this,likeList);
    listView.addHeaderView(header);
    listView.setAdapter(adapter);
    
	
}


private void findViews() {
  
    findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View paramView) {
        VideoActivity.this.finish();
      }
    });
  
	ImageView ivPlay = (ImageView) findViewById(R.id.iv_play);
	ImageLoader.getInstance().displayImage(bean.getUrlImage(), ivPlay);
	ivPlay.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        Intent intent = new Intent(context,VideoPlayActivity.class);
        intent.putExtra("video", bean);
        startActivity(intent);
      }
    });
	
	ImageView ivPlay1 = (ImageView) findViewById(R.id.iv_play1);
	ivPlay1.setOnClickListener(new OnClickListener() {
	  @Override
	  public void onClick(View arg0) {
	    Intent intent = new Intent(context,VideoPlayActivity.class);
	    intent.putExtra("video", bean);
	    startActivity(intent);
	  }
	});
	
}
  


//start----------------------------------------------------------

private CommonLog log = LogFactory.createLog();

private final int SHOW_RELATIVE = 1;
private final int HIDE_RELATIVE = 2;
private final int SHOW_PROGRESS = 3;
private final int HIDE_PROGRESS = 4;
private final int PLAY_SNED_IR_CODE_KEY_TONE = 204;
private final int PLAY_VIDEO = 5;
private final int TURN_NEXT_SOURCE = 6;
private final int NO_USED_SOURCE = 7;

private float screenScale = 3 / 4;
private TextView liveback;
private TextView title;
private RelativeLayout liveRel;
private ImageView btnfullScreen;
private ImageView btnPlay;
private TextView tvTime;
private VideoBean videoBean;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private PowerManager.WakeLock mWakeLock = null;
private Timer mTimer=new Timer();
private boolean isExitLivePlay = false;
private String currentPos;

/******************************************************* 
 * 通过定时器和Handler来更新进度条 
 ******************************************************/  
TimerTask mTimerTask = new TimerTask() {  
    @Override  
    public void run() {  
        if(mPlayer==null)  
            return;  
        if (mPlayer.isPlaying() && seekBar.isPressed() == false) {  
            handler.sendEmptyMessage(0);  
        }  
    }  
};  
  

Handler handler = new Handler(){
  public void handleMessage(android.os.Message msg) {
    switch (msg.what) {
      case 0:
      {
        int position = mPlayer.getCurrentPosition();  
        int duration = mPlayer.getDuration();  
        
        //Log.e("TAG", "duration=====>" + duration);
        int allTime = duration /1000;
        
        if (position/1000 < 60) {
          if(position/1000 < 10){
        	  currentPos = "00:0" + position/1000;
          } else {
        	  currentPos = "00:" + position/1000;
          }
        } else {
          currentPos = (position/1000/60) + ":" + (position/1000 % 60);
        }
        
        String min = "";
        if(allTime/60 < 10){
        	min = "0"+allTime/60;
        } else {
        	min = "" + allTime/60;
        }
        String sec = "";
        if(allTime%60 < 10){
        	sec = "0"+allTime%60;
        } else {
        	sec = "" + allTime%60;
        }
        
        tvTime.setText(currentPos + "/" + min + ":" + sec);
        
//        if (duration > 0) {  
//          long pos = seekBar.getMax() * position / duration;  
//          seekBar.setProgress((int) pos);  
//        }  
        
      }
        break;
        
      case SHOW_RELATIVE:
        showRelativeLayout();
        break;

      case HIDE_RELATIVE:
        hideRelativeLayout();
        break;

      case SHOW_PROGRESS:
        ((ProgressBar) findViewById(R.id.program_live_probar)).setVisibility(View.VISIBLE);
        break;

      case HIDE_PROGRESS:
        ((ProgressBar) findViewById(R.id.program_live_probar)).setVisibility(View.INVISIBLE);
        hideRelativeLayout();
        break;

      case PLAY_SNED_IR_CODE_KEY_TONE:
        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        // playSendIrCodeKeyTone();
        // }
        // }).start();
        break;

      case TURN_NEXT_SOURCE:
        //obtainVideFromUrl();
        break;

      case PLAY_VIDEO:
        playLiveRadio();
        break;

      case NO_USED_SOURCE:
        errorPlayDismiss(getString(R.string.program_no_live_source));
        break;


      default:
        break;
    }
    
  };
  
};


protected void initPlayer() {
  
 //設置不鎖屏
  PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
  mWakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "XYTEST");
  mWakeLock.acquire();
  
  videoBean = bean;
  findPlayerViews();
  initValues();
  setListeners();
  mTimer.schedule(mTimerTask,0, 1000);
  
  
}


@Override
protected void onResume() {
  
  if (mWakeLock == null) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "XYTEST");
    mWakeLock.acquire();
  }

  if (null != mPlayer && !mPlayer.isPlaying()) {
    mPlayer.start();
  }
  createMediaplayer();
  super.onResume();
}


private void setListeners() {
  
  //
  mSurfaceView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (View.INVISIBLE == liveRel.getVisibility()) {
        handler.sendEmptyMessage(SHOW_RELATIVE);
      } else {
        handler.sendEmptyMessage(HIDE_RELATIVE);
      }
    }
  });
  
  
  btnfullScreen.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    	Intent intent = new Intent(context,VideoPlayActivity.class);
	    intent.putExtra("video", bean);
	    startActivity(intent);
    }
  });
  
  btnPlay.setOnClickListener(new OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		playOrPause();
	}
  });
  
}

private void playOrPause() {
    if (videoIsPlay) {
      if (null != mPlayer && mPlayer.isPlaying()) {
        log.d("playOrPause mPlayer1.pause() ");
        mPlayer.pause();
        videoIsPlay = false;
        btnPlay.setBackgroundResource(R.drawable.play);
      }
    } else {
      if (null != mPlayer) {
        log.d("playOrPause mPlayer1.start() ");
        mPlayer.start();
        videoIsPlay = true;
        btnPlay.setBackgroundResource(R.drawable.pause);
        log.i("times:" + mPlayer.getDuration());
      }
    }
  }

private void initValues() {
  
  //标题
  title.setText(videoBean.getTitle());
  
  mSurfaceHolder = mSurfaceView.getHolder();
  mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
  mSurfaceHolder.addCallback(new Callback() {
    @Override
    public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder) {
    }
    @Override
    public void surfaceCreated(SurfaceHolder paramSurfaceHolder) {
      handler.sendEmptyMessage(PLAY_VIDEO);
    }
    @Override
    public void surfaceChanged(SurfaceHolder paramSurfaceHolder, int paramInt1, int paramInt2,
        int paramInt3) {
    }
  });


  
}

private void findPlayerViews() {
  title = (TextView) findViewById(R.id.title);
  liveRel = (RelativeLayout) findViewById(R.id.program_live_rel);
  btnfullScreen = (ImageView) findViewById(R.id.full_screen);
  tvTime = (TextView) findViewById(R.id.tv_time);
  mSurfaceView = (SurfaceView) findViewById(R.id.program_live_play_surface);
  seekBar = (SeekBar) findViewById(R.id.program_live_seekbar);
  btnPlay = (ImageView) findViewById(R.id.program_live_player);
}

boolean videoIsPlay;
private MediaPlayer mPlayer;

private void hideRelativeLayout() {
  liveRel.setVisibility(View.INVISIBLE);
}

private void showRelativeLayout() {
  liveRel.setVisibility(View.VISIBLE);
}

//創建播放器
private void createMediaplayer() {
  if (mPlayer == null) {
    Log.d("TAG","new a mediaplayer");
    mPlayer = new MediaPlayer();
    mPlayer.setOnBufferingUpdateListener(bufferListener);
    mPlayer.setOnCompletionListener(completionListener);
    mPlayer.setOnErrorListener(errorListener);
    mPlayer.setOnInfoListener(infoListener);
    mPlayer.setOnPreparedListener(prepareListener);
    mPlayer.setOnVideoSizeChangedListener(sizeChangedListener);
  }
}


private void errorPlayDismiss(String message) {
  Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}

MediaPlayer.OnBufferingUpdateListener bufferListener = new OnBufferingUpdateListener() {
  @Override
  public void onBufferingUpdate(MediaPlayer mp, int percent) {
    
    seekBar.setSecondaryProgress(percent);  
    int currentProgress=seekBar.getMax()*mPlayer.getCurrentPosition()/mPlayer.getDuration();  
    
    Log.e(currentProgress+"% play", percent + "% buffer");  
    
    //tvTime.setText("load:" + percent + tvTime.getText());
  }
};

MediaPlayer.OnErrorListener errorListener = new OnErrorListener() {
  @Override
  public boolean onError(MediaPlayer mp, int what, int extra) {
    if (100 == what) {
      log.d("mPlayer1 server had died ");
    }
    if (isExitLivePlay) {
      log.d("=======LivePlayActivity is finished=======");
      return false;
    }
 
    switch (extra) {
      case -1004:// MediaPlayer.MEDIA_ERROR_IO
        // Toast.makeText(context, "I/O error!please check out", Toast.LENGTH_LONG).show();
        errorPlayDismiss(getString(R.string.program_live_ioerror));
        break;
      case -1007:// MediaPlayer.MEDIA_ERROR_MALFORMED
        // Toast.makeText(context, "MEDIA_ERROR_MALFORMED error!please check out",
        // Toast.LENGTH_LONG).show();
        errorPlayDismiss(getString(R.string.program_live_malformederror));
        break;
      case -1010:// MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
        // Toast.makeText(context, "MEDIA_ERROR_UNSUPPORTED error!please check out",
        // Toast.LENGTH_LONG).show();
        errorPlayDismiss(getString(R.string.program_live_unsupportederror));
        break;
      case -110:// MediaPlayer.MEDIA_ERROR_TIMED_OUT:
        // Toast.makeText(context, "MEDIA_ERROR_TIMED_OUT error!please check out",
        // Toast.LENGTH_LONG).show();
        errorPlayDismiss(getString(R.string.program_live_timeouterror));
        break;

      default:
        // Toast.makeText(context, "unknown play error!please check out",
        // Toast.LENGTH_LONG).show();
        errorPlayDismiss(getString(R.string.program_live_unkownerror));
        break;
    }

    return false;
  }
};

MediaPlayer.OnPreparedListener prepareListener = new OnPreparedListener() {
  @Override
  public void onPrepared(MediaPlayer mp) {
    
    log.i("prepareListener times:" + mPlayer.getDuration()/1000);
    
    mPlayer.start();
    
    if (mPlayer.isPlaying()) {
      log.d("prepareListener isPlaying");
      mPlayer.setScreenOnWhilePlaying(true);
    }
  }
};

MediaPlayer.OnCompletionListener completionListener = new OnCompletionListener() {
  @Override
  public void onCompletion(MediaPlayer mp) {
    log.i("MediaPlayer.OnCompletionListener===>onCompletion " + mp.getDuration() );
  }
};

MediaPlayer.OnVideoSizeChangedListener sizeChangedListener = new OnVideoSizeChangedListener() {
  @Override
  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    log.d("onVideoSizeChanged width = " + width + " height = " + height);
    screenScale = (float) height / width;
    handler.sendEmptyMessage(HIDE_PROGRESS);
  }
};

MediaPlayer.OnInfoListener infoListener = new OnInfoListener() {
  @Override
  public boolean onInfo(MediaPlayer mp, int what, int extra) {
    log.d("onInfo what = " + what + " extra = " + extra);
    return false;
  }
};

private SeekBar seekBar;

private void playLiveRadio() {
  if (null == mPlayer) {
    log.d("mPlayer1 is null ");
    return;
  }

  // !mSurfaceHolder1.getSurface().isValid()
  log.d("mSurfaceHolder1.getSurface().isValid() : " + mSurfaceHolder.getSurface().isValid());
  if (null == mSurfaceHolder || null == mSurfaceHolder.getSurface()) {
    log.d("mSurfaceHolder1 is null or mSurfaceHolder1.getSurface() is null ");
    return;
  }

  if (null != mPlayer) {
    log.d("mPlayer1 reset ");
    mPlayer.reset();
  }

  if (isExitLivePlay) {
    log.d("isExitLivePlay : " + isExitLivePlay);
    return;
  }

  mPlayer.setDisplay(mSurfaceHolder);

  try {
    log.d("--------------> strVideoURL : " + videoBean.getUrlFlv());
    mPlayer.setDataSource(context, Uri.parse(videoBean.getUrlFlv()));
    mPlayer.prepareAsync();
    log.i("times:---->" + mPlayer.getDuration());
    
    //handler.sendEmptyMessage(HIDE_RELATIVE);
    
  } catch (IllegalArgumentException e) {
    log.e("ex : " + e.toString());
  } catch (IOException e) {
    log.e("ex : " + e.toString());
  }
}

@Override
protected void onPause() {
  log.i("************* onPause");
  if (null != mPlayer && mPlayer.isPlaying()) {
    log.d("playOrPause mPlayer1.pause() ");
    mPlayer.pause();
  }
  super.onPause();
}

@Override
protected void onStop() {
  log.i("************* onStop");
  if (mWakeLock != null) {
    mWakeLock.release();
    mWakeLock = null;
  }

  if (null != mPlayer) {
    mPlayer.stop();
    // mPlayer1.reset();
    mPlayer.release();
    mPlayer = null;
  }
  super.onStop();
}

@Override
protected void onDestroy() {
  log.i("************* onDestroy");
  // RunningActivityMng.instance().removeActivity(ProgramLivePlayActivity.this);
  try {
    if (mPlayer != null) {
      mPlayer.stop();
      // mMediaPlayer.reset();
      mPlayer.release();
      mPlayer = null;
    }
  } catch (Exception ex) {
    log.e("ex: " + ex.toString());
  }

  releaseMemory();
  super.onDestroy();
}

private void releaseMemory() {

  if (mWakeLock != null) {
    mWakeLock.release();
    mWakeLock = null;
  }
  try {
    if (null != mPlayer) {
      log.d("============mPlayer1 reset==========");
      mPlayer.stop();
      // mPlayer1.reset();
      mPlayer.release();
      mPlayer = null;
    }
  } catch (Exception e) {
    log.d("ex : " + e.toString());
  }
  if (null != mSurfaceView) {
    log.d("mSurfaceView1 is not null , release mSurfaceView1");
    mSurfaceView = null;
  }
  if (null != mSurfaceHolder) {
    log.d("mSurfaceHolder1 is not null , release mSurfaceHolder1");
    mSurfaceHolder = null;
  }
}





  
  
  

}
